<?php

/**
 * This file is part of easyCMS.
 *
 * (c) 2023 easyCMS <easyCMS@easycms.net.cn>
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace app\admin\controller;

use app\admin\model\BaseModel;
use app\admin\model\SystemAdmin;
use app\admin\model\SystemAdminRole;
use app\admin\model\SystemRole;
use app\admin\validate\UserValidate;
use app\common\Util;
use Exception;
use support\Db;
use support\Request;

class UserController
{
    /**
     * 用户列表
     */
    #[permits('admin:user:list')]
    public function index(Request $request): \support\Response
    {
        return view('user/userList');
    }

    /**
     * 用户列表
     */
    #[permits('admin:user:list')]
    public function userListData(Request $request): \support\Response
    {
        $users = SystemAdmin::select(DB::raw(Db::getConfig('prefix') . 'system_admin.*,group_concat(' . Db::getConfig('prefix') . 'r.role_id) as roles'))
            ->leftJoin('system_admin_role as r', 'system_admin.id', '=', 'r.userid')
            ->where('system_admin.status', BaseModel::STATUS_NORMAL)
            ->groupBy('system_admin.id')
            ->orderBy('system_admin.id', 'DESC')->get()->toArray();
        $roles    = SystemRole::select(['id', 'name'])->orderBy('id', 'ASC')->get()->toArray();
        $rolesArr = [];

        foreach ($roles as $r) {
            $rolesArr[$r['id']] = $r['name'];
        }

        for ($i = 0; $i < count($users); $i++) {
            $roleIds = $users[$i]['roles'];
            if ($roleIds === null || $roleIds === '') {
                continue;
            }
            $roleIdArr = explode(',', $roleIds);
            $roleNames = '';

            foreach ($roleIdArr as $r) {
                if ($rolesArr[$r] !== '') {
                    $roleNames .= $rolesArr[$r] . ',';
                }
            }
            $users[$i]['roles'] = trim($roleNames, ',');
        }

        return json(['code' => 0, 'msg' => '', 'count' => 0, 'data' => $users]);
    }

    /**
     * 用户新增
     */
    #[permits('admin:user:add')]
    public function userAdd(Request $request): \support\Response
    {
        $data['user']     = new SystemAdmin();
        $data['roles']    = SystemRole::select(['id as value', 'name'])->where('status', BaseModel::STATUS_NORMAL)->orderBy('id', 'ASC')->get()->toArray();
        $data['hasRoles'] = '';

        return view('user/userEdit', $data);
    }

    /**
     * 用户新增
     */
    #[permits('admin:user:add')]
    public function doUserAdd(Request $request): \support\Response
    {
        $code = 0;
        $msg  = '';

        $postData = [
            'roles'    => $request->post('roles'),
            'username' => $request->post('username'),
            'nickname' => $request->post('nickname'),
            'password' => $request->post('password'),
        ];

        $validate = new UserValidate();
        if ($validate->check($postData)) {
            $user           = new SystemAdmin();
            $user->username = $postData['username'];
            $user->nickname = $postData['nickname'];
            if ($postData['password'] !== '') {
                $user->password = Util::passwordEncode($postData['password']);
            }
            $user->user_type = SystemAdmin::NORMAL_ADMIN;
            $user->is_lock   = BaseModel::LOCK_NO;
            $user->status    = BaseModel::STATUS_NORMAL;
            Db::beginTransaction();

            try {
                $user->save();
                // 添加新角色
                $user->roles()->attach(explode(',', $postData['roles']));
                Db::commit();
                $msg = '增加成功';
            } catch (Exception $e) {
                Db::rollBack();
                $code = 1;
                $msg  = '失败';
            }
        } else {
            $code = 1;
            $msg  = $validate->getError();
        }

        return json(['code' => $code, 'msg' => $msg]);
    }

    /**
     * 用户修改
     */
    #[permits('admin:user:edit')]
    public function userEdit(Request $request): \support\Response
    {
        $id           = $request->get('id');
        $data['user'] = SystemAdmin::find($id);
        $rolesList    = $data['user']->roles()->get()->toArray();
        $hasRoles     = '';

        foreach ($rolesList as $r) {
            $hasRoles .= $r['id'] . ',';
        }
        $data['hasRoles'] = $hasRoles;
        $data['roles']    = SystemRole::select(['id as value', 'name'])->where('status', BaseModel::STATUS_NORMAL)->orderBy('id', 'ASC')->get()->toArray();

        return view('user/userEdit', $data);
    }

    /**
     * 用户修改
     */
    #[permits('admin:user:edit')]
    public function doUserEdit(Request $request): \support\Response
    {
        $code = 0;
        $msg  = '';

        $postData = [
            'id'       => $request->post('id'),
            'roles'    => $request->post('roles'),
            'nickname' => $request->post('nickname'),
            'password' => $request->post('password'),
        ];

        $validate = new UserValidate();
        if ($validate->scene('edit')->check($postData)) {
            $user = SystemAdmin::find($postData['id']);
            if ($user !== null && $user->id > 0) {
                if ($user->id === 1) {
                    $code = 1;
                    $msg  = '超管不能修改';
                } else {
                    $user->nickname = $postData['nickname'];
                    if ($postData['password'] !== '') {
                        $user->password = Util::passwordEncode($postData['password']);
                    }

                    Db::beginTransaction();

                    try {
                        $user->save();
                        // 删除旧角色
                        SystemAdminRole::where('userid', $user->id)->delete();
                        // 新添加角色
                        $user->roles()->attach(explode(',', $postData['roles']));
                        Db::commit();
                        $msg = '修改成功';
                    } catch (Exception $e) {
                        Db::rollBack();
                        $code = 1;
                        $msg  = '失败';
                    }
                }
            } else {
                $code = 1;
                $msg  = '该角色不存在';
            }
        } else {
            $code = 1;
            $msg  = $validate->getError();
        }

        return json(['code' => $code, 'msg' => $msg]);
    }

    /**
     * 用户删除
     */
    #[permits('admin:user:delete')]
    public function userDelete(Request $request): \support\Response
    {
        $code = 0;
        $msg  = '';
        $id   = $request->post('id');

        if ((int) $id === 1) {
            $code = 1;
            $msg  = '不能删除超级管理员';
        } else {
            $user = SystemAdmin::find($id);
            if ($user !== null && $user->id > 0) {
                try {
                    // 删除角色关联关系
                    SystemAdminRole::where('userid', $user->id)->delete();
                    // 删除账号
                    $user->delete();
                    Db::commit();
                    $msg = '删除成功';
                } catch (Exception $e) {
                    Db::rollBack();
                    $code = 1;
                    $msg  = '删除失败';
                }
            }
        }

        return json(['code' => $code, 'msg' => $msg]);
    }
}
